using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class 开始游戏 : MonoBehaviour
{
    public string serverIp = "127.0.0.1"; // 服务器IP地址
    public int serverPort = 8080; // 服务器端口号
    public GameObject 提示框; // 错误提示框

    // 定义Log为Debug.Log
    public static void Log(string message)
    {
        Debug.Log(message);
    }

    // 按钮点击事件
    public void Start()
    {
        Button button = GetComponent<Button>();
        button.onClick.AddListener(OnClick);
    }

    // 按钮点击事件处理函数
    public void OnClick()
    {
        // 发送请求
        string request = "get";
        StartCoroutine(SendRequest(request));
    }
    // 发送请求协程
    IEnumerator SendRequest(string request)
    {
        // 创建TcpClient并连接到服务器
        using (TcpClient client = new TcpClient())
        {
            try
            {
                client.Connect(serverIp, serverPort); // 连接到服务器
                Log("Connected to server.");

                // 获取网络流
                NetworkStream stream = client.GetStream();

                // 将请求转换为字节数据并发送
                byte[] requestBytes = Encoding.UTF8.GetBytes(request);
                stream.Write(requestBytes, 0, requestBytes.Length);
                Log("Request sent: " + request);

                // 接收服务器响应
                byte[] responseBytes = new byte[1024];
                int bytesRead = stream.Read(responseBytes, 0, responseBytes.Length);
                string response = Encoding.UTF8.GetString(responseBytes, 0, bytesRead);
                Log("Server response: " + response);
                if (response == "ok")
                {
                    // 服务器响应成功，跳转到游戏场景
                    SceneManager.LoadScene("战斗");
                }
                else
                {
                    // 服务器响应失败，弹出提示框
                    // 添加"提示框"预制体到"GUI"画布
                    GameObject 错误提示框 = GameObject.Instantiate(提示框, GameObject.Find("GUI").transform);
                    查找子物体文本.查找文本(错误提示框.transform, "errortext").text = string.Format("error: {0}", response);
                }
            }
            catch (Exception e)
            {
                Log("Error: " + e.Message);
                // 添加"提示框"预制体到"GUI"画布
                GameObject 错误提示框 = GameObject.Instantiate(提示框, GameObject.Find("GUI").transform);
                // 设置提示框的文本内容"errortext"
                查找子物体文本.查找文本(错误提示框.transform, "errortext").text = string.Format("error: {0}", e.Message); 
            }
            yield return null;
        }
    }
}
